package com.energyfuture.auth.controller;


import com.energyfuture.auth.form.LoginBody;
import com.energyfuture.auth.service.VerificationCodeService;
import com.energyfuture.common.core.domain.R;
import com.energyfuture.common.core.text.UUID;
import com.energyfuture.common.core.utils.StringUtils;
import com.energyfuture.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * token 控制
 * 
 * @author energyfuture
 */
@RestController
public class SmsApiController
{


    @Autowired
    private VerificationCodeService verificationCodeService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @PostMapping("send/{phone}")
    public String code( String phone){
        String code=redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return phone + ":"+code+"已存在，未过期";
        }
        code= UUID.randomUUID().toString().substring(0,4);
        HashMap<String,Object> param=new HashMap<String, Object>();
        param.put("code",code);
        boolean isSend=verificationCodeService.send(phone,"模板Code",param);
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return phone + ":"+code+"发送成功！";
        }
        else{
            return "发送失败";
        }
    }

    /**
     * 检查手机验证码
     * @param code 验证码
     * @return
     */
    @PostMapping("checkVerificationCode")
    public R<?> checkVerificationCode(String code,String phone)
    {
        // 检查手机验证码
        boolean flag = verificationCodeService.checkVerificationCode(redisTemplate,code,phone);
        if(flag){
            return R.ok();
        }else{
            return R.fail();
        }
    }


}
